import QtQuick 2.15
import QtQuick.Controls 2.15
import TSCore.Presentation 1.0
import "qrc:/qml/styles" as Styles
import "qrc:/qml/components" as Components

Rectangle {
    id: liveMapView

    // 直接使用全局上下文属性
    property var agvListModel: null  // AGV Model
    property bool showAgvLabels: true
    property bool showPaths: true
    property bool showStations: true
    property var pendingFocusRequest: null

    // Debug: 监听全局 MapViewModel
    Component.onCompleted: {
        console.log("LiveMapView: Using GlobalMapViewModel:", GlobalMapViewModel ? "exists" : "null")
        if (GlobalMapViewModel) {
            console.log("LiveMapView: GlobalMapViewModel.mapName:", GlobalMapViewModel.mapName || "no mapName")
            console.log("LiveMapView: GlobalMapViewModel.isMapLoaded:", GlobalMapViewModel.isMapLoaded || false)
            updateMapData()
        }
    }

    // 监听 GlobalMapViewModel 的信号
    Connections {
        target: GlobalMapViewModel

        function onMapChanged() {
            console.log("LiveMapView: Received mapChanged signal from GlobalMapViewModel")
            updateMapData()
            focusPendingPointIfAny()
        }

        function onMapLoadedChanged() {
            console.log("LiveMapView: Received mapLoadedChanged signal, isMapLoaded:",
                       GlobalMapViewModel ? GlobalMapViewModel.isMapLoaded : false)
            if (GlobalMapViewModel && GlobalMapViewModel.isMapLoaded) {
                updateMapData()
            }
            focusPendingPointIfAny()
        }
    }

    // 更新地图数据的函数
    function updateMapData() {
        if (GlobalMapViewModel && GlobalMapViewModel.mapDisplayData && GlobalMapViewModel.isMapLoaded) {
            console.log("LiveMapView: Updating map data for map:", GlobalMapViewModel.mapName)
            mapBackground.mapData = GlobalMapViewModel.mapDisplayData
        } else {
            console.log("LiveMapView: Cannot update map data - GlobalMapViewModel:",
                       GlobalMapViewModel ? "exists" : "null",
                       "isMapLoaded:", GlobalMapViewModel ? GlobalMapViewModel.isMapLoaded : false)
        }
    }

    // 默认样式
    color: Styles.Theme.backgroundSecondary
    border.color: Styles.Theme.border
    border.width: 1
    radius: Styles.Theme.radiusNormal

    // 信号
    signal agvClicked(int agvNumber)
    signal stationClicked(string stationId)
    signal mapClicked(point position)

    // 聚焦到指定位置
    function focusOnPosition(x, y) {
        mapBackground.centerOnPoint(Qt.point(x, y))
    }

    // 聚焦到指定 AGV
    function focusOnAgv(agvNumber) {
        if (!agvListModel) return

        var agvData = agvListModel.getAgvDataByNumber
                ? agvListModel.getAgvDataByNumber(agvNumber)
                : null
        if (!agvData) {
            for (var i = 0; i < agvListModel.rowCount(); i++) {
                var fallback = agvListModel.getAgvData(i)
                if (fallback && fallback.agvNumber === agvNumber) {
                    agvData = fallback
                    break
                }
            }
        }
        if (!agvData) return

        var x = agvData.x || 0
        var y = agvData.y || 0
        if (x === 0 && y === 0) return
        var point = Qt.point(x, y)

        if (GlobalMapViewModel) {
            var targetMap = agvData.currentMap || ""
            if (targetMap && !isSameMap(GlobalMapViewModel.mapName || "", targetMap)) {
                pendingFocusRequest = { point: point }
                var targetFloor = GlobalMapViewModel.getFloorForMap
                        ? GlobalMapViewModel.getFloorForMap(targetMap)
                        : -1
                if (targetFloor >= 0
                        && targetFloor !== GlobalMapViewModel.currentFloor) {
                    GlobalMapViewModel.switchToFloor(targetFloor)
                } else if (targetMap && GlobalMapViewModel.loadMap) {
                    GlobalMapViewModel.loadMap(targetMap)
                }
                return
            }
            if (!GlobalMapViewModel.isMapLoaded) {
                pendingFocusRequest = { point: point }
                return
            }
        }

        pendingFocusRequest = null
        Qt.callLater(function () {
            mapBackground.centerOnPoint(point)
        })
    }

    function isSameMap(mapA, mapB) {
        var normalize = function (name) {
            if (!name) return ""
            var normalized = name.toString().trim()
            var slash = Math.max(normalized.lastIndexOf("/"),
                                 normalized.lastIndexOf("\\"))
            if (slash >= 0) normalized = normalized.slice(slash + 1)
            var dot = normalized.lastIndexOf(".")
            if (dot > 0) normalized = normalized.slice(0, dot)
            return normalized.toLowerCase()
        }
        return normalize(mapA) === normalize(mapB)
    }

    function focusPendingPointIfAny() {
        if (!pendingFocusRequest) return
        if (!GlobalMapViewModel || !GlobalMapViewModel.isMapLoaded) return
        var targetPoint = pendingFocusRequest.point
        pendingFocusRequest = null
        Qt.callLater(function () {
            mapBackground.centerOnPoint(targetPoint)
        })
    }

    // 地图背景渲染器（包含 AGV 绘制）
    MapBackgroundItem {
        id: mapBackground
        anchors.fill: parent
        anchors.margins: 1

        // 地图数据
        mapData: GlobalMapViewModel ? GlobalMapViewModel.mapDisplayData : null

        // AGV 数据模型（直接传递）
        agvListModel: liveMapView.agvListModel
        filterAgvByMap: true

        // AGV 显示配置
        showAgvLabels: liveMapView.showAgvLabels
        agvIconSize: 30.0

        // 地图样式配置
        backgroundColor: Styles.Theme.backgroundSecondary
        stationColor: "#C9F970"
        pathColor: "#409F41"
        areaColor: "#E0E0E0"
        stationSize: 0.7
        pathWidth: 6.0
        scaleFactor: 30.0

        // 地图事件处理
        onStationClicked: function(stationName, position) {
            console.log("Station clicked:", stationName)
            liveMapView.stationClicked(stationName)
        }

        onAgvClicked: function(agvNumber, position) {
            console.log("AGV clicked:", agvNumber)
            liveMapView.agvClicked(agvNumber)
        }

        onSingleClick: function(position) {
            console.log("Map clicked at:", position.x, position.y)
            liveMapView.mapClicked(position)
        }

        // 初始化地图
        onMapDataChanged: {
            if (mapData && mapData.mapName) {
                console.log("Initializing live map:", mapData.mapName)
                initMap(mapData.mapName)
            }
        }
    }

    // 地图控制层
    Column {
        anchors.top: parent.top
        anchors.left: parent.left
        anchors.margins: Styles.Theme.spacingNormal
        spacing: Styles.Theme.spacingSmall
        z: 100

        // 地图信息显示
        Rectangle {
            width: infoColumn.width + Styles.Theme.spacingNormal * 2
            height: infoColumn.height + Styles.Theme.spacingSmall * 2
            color: Styles.Theme.surface
            border.color: Styles.Theme.border
            border.width: 1
            radius: Styles.Theme.radiusSmall
            opacity: 0.9

            Column {
                id: infoColumn
                anchors.centerIn: parent
                spacing: 2

                Text {
                    text: qsTr("地图: %1").arg(GlobalMapViewModel ? (GlobalMapViewModel.mapName || qsTr("未加载")) : qsTr("无"))
                    color: Styles.Theme.textPrimary
                    font.pixelSize: Styles.Theme.fontSizeSmall
                    font.weight: Styles.Theme.fontWeightMedium
                }

                Text {
                    visible: GlobalMapViewModel && GlobalMapViewModel.isMapLoaded
                    text: qsTr("分辨率: %1").arg(GlobalMapViewModel ? GlobalMapViewModel.mapResolution.toFixed(2) : "0.00")
                    color: Styles.Theme.textSecondary
                    font.pixelSize: Styles.Theme.fontSizeSmall
                }

                Text {
                    text: qsTr("AGV数量: %1").arg(liveMapView.agvListModel ? liveMapView.agvListModel.rowCount() : 0)
                    color: Styles.Theme.textSecondary
                    font.pixelSize: Styles.Theme.fontSizeSmall
                }
            }
        }

        // 快速操作按钮
        Column {
            spacing: Styles.Theme.spacingXSmall

            Components.ActionButton {
                size: "small"
                text: qsTr("适应")
                iconSource: "🔍"
                buttonType: "secondary"
                onClicked: mapBackground.fitToView()
            }

            Components.ActionButton {
                size: "small"
                text: qsTr("重置")
                iconSource: "↻"
                buttonType: "secondary"
                onClicked: mapBackground.resetView()
            }

            Components.ActionButton {
                size: "small"
                text: qsTr("刷新")
                iconSource: "qrc:/icons/refresh.svg"
                buttonType: "secondary"
                onClicked: {
                    if (GlobalMapViewModel) {
                        GlobalMapViewModel.refreshMapData()
                    }
                }
            }
        }

        // 楼层切换按钮组
        Rectangle {
            id: floorSwitchContainer
            property bool hasLoadedFloors: GlobalMapViewModel && GlobalMapViewModel.loadedFloors && GlobalMapViewModel.loadedFloors.length > 0
            width: floorButtonsRow.width + Styles.Theme.spacingSmall * 2
            height: floorButtonsRow.height + Styles.Theme.spacingXSmall * 2
            color: Styles.Theme.surface
            border.color: Styles.Theme.border
            border.width: 1
            radius: Styles.Theme.radiusSmall
            opacity: 0.9
            visible: GlobalMapViewModel

            Row {
                id: floorButtonsRow
                anchors.centerIn: parent
                spacing: Styles.Theme.spacingXSmall

                Text {
                    anchors.verticalCenter: parent.verticalCenter
                    text: qsTr("楼层:")
                    color: Styles.Theme.textSecondary
                    font.pixelSize: Styles.Theme.fontSizeSmall
                }

                Repeater {
                    model: floorSwitchContainer.hasLoadedFloors ? GlobalMapViewModel.loadedFloors : []

                    Components.ActionButton {
                        width: 40
                        height: 28
                        text: modelData.toString() + "F"
                        buttonType: (GlobalMapViewModel && GlobalMapViewModel.currentFloor === modelData) ? "primary" : "secondary"
                        onClicked: {
                            if (GlobalMapViewModel) {
                                console.log("Switching to floor:", modelData)
                                GlobalMapViewModel.switchToFloor(modelData)
                            }
                        }
                    }
                }

                Text {
                    visible: !floorSwitchContainer.hasLoadedFloors
                    text: qsTr("正在加载楼层...")
                    color: Styles.Theme.textSecondary
                    font.pixelSize: Styles.Theme.fontSizeSmall
                }
            }
        }
    }

    // 图例
    Rectangle {
        anchors.bottom: parent.bottom
        anchors.right: parent.right
        anchors.margins: Styles.Theme.spacingNormal
        width: legendColumn.width + Styles.Theme.spacingNormal * 2
        height: legendColumn.height + Styles.Theme.spacingSmall * 2
        color: Styles.Theme.surface
        border.color: Styles.Theme.border
        border.width: 1
        radius: Styles.Theme.radiusSmall
        opacity: 0.9

        Column {
            id: legendColumn
            anchors.centerIn: parent
            spacing: Styles.Theme.spacingXSmall

            Text {
                text: qsTr("图例")
                color: Styles.Theme.textPrimary
                font.pixelSize: Styles.Theme.fontSizeSmall
                font.weight: Styles.Theme.fontWeightMedium
            }

            // AGV状态图例
            Column {
                spacing: 2

                Row {
                    spacing: Styles.Theme.spacingXSmall
                    Rectangle { width: 12; height: 12; radius: 6; color: Styles.Theme.agvIdle }
                    Text { text: qsTr("空闲"); color: Styles.Theme.textSecondary; font.pixelSize: 10 }
                }

                Row {
                    spacing: Styles.Theme.spacingXSmall
                    Rectangle { width: 12; height: 12; radius: 6; color: Styles.Theme.agvExecuting }
                    Text { text: qsTr("执行中"); color: Styles.Theme.textSecondary; font.pixelSize: 10 }
                }

                Row {
                    spacing: Styles.Theme.spacingXSmall
                    Rectangle { width: 12; height: 12; radius: 6; color: Styles.Theme.agvCharging }
                    Text { text: qsTr("充电中"); color: Styles.Theme.textSecondary; font.pixelSize: 10 }
                }

                Row {
                    spacing: Styles.Theme.spacingXSmall
                    Rectangle { width: 12; height: 12; radius: 6; color: Styles.Theme.agvBlocked }
                    Text { text: qsTr("阻挡"); color: Styles.Theme.textSecondary; font.pixelSize: 10 }
                }

                Row {
                    spacing: Styles.Theme.spacingXSmall
                    Rectangle { width: 12; height: 12; radius: 6; color: Styles.Theme.agvLocked }
                    Text { text: qsTr("急停/锁定"); color: Styles.Theme.textSecondary; font.pixelSize: 10 }
                }

                Row {
                    spacing: Styles.Theme.spacingXSmall
                    Rectangle { width: 12; height: 12; radius: 6; color: Styles.Theme.agvError }
                    Text { text: qsTr("故障"); color: Styles.Theme.textSecondary; font.pixelSize: 10 }
                }
            }

            // 区域占用图例
            Column {
                spacing: 2
                Row {
                    spacing: Styles.Theme.spacingXSmall
                    Rectangle { width: 12; height: 12; radius: 2; color: "#C9F970"; border.color: "#409F41"; border.width: 1 }
                    Text { text: qsTr("区域空闲"); color: Styles.Theme.textSecondary; font.pixelSize: 10 }
                }
                Row {
                    spacing: Styles.Theme.spacingXSmall
                    Rectangle { width: 12; height: 12; radius: 2; color: "#FFD54F"; border.color: "#FFA000"; border.width: 1 }
                    Text { text: qsTr("区域预占"); color: Styles.Theme.textSecondary; font.pixelSize: 10 }
                }
                Row {
                    spacing: Styles.Theme.spacingXSmall
                    Rectangle { width: 12; height: 12; radius: 2; color: "#FF7043"; border.color: "#E64A19"; border.width: 1 }
                    Text { text: qsTr("区域占用"); color: Styles.Theme.textSecondary; font.pixelSize: 10 }
                }
            }
        }
    }

    // 状态指示器
    Rectangle {
        anchors.bottom: parent.bottom
        anchors.left: parent.left
        anchors.margins: Styles.Theme.spacingNormal
        width: statusText.width + 16
        height: statusText.height + 8
        radius: Styles.Theme.radiusSmall
        color: (GlobalMapViewModel && GlobalMapViewModel.isMapLoaded) ? Styles.Theme.success : Styles.Theme.danger

        Text {
            id: statusText
            anchors.centerIn: parent
            text: (GlobalMapViewModel && GlobalMapViewModel.isMapLoaded) ? qsTr("地图已加载") : qsTr("地图未加载")
            color: Styles.Theme.textOnPrimary
            font.pixelSize: 10
        }
    }

    // 缩放控制
    Column {
        anchors.right: parent.right
        anchors.verticalCenter: parent.verticalCenter
        anchors.rightMargin: Styles.Theme.spacingNormal
        spacing: 2

        Components.ActionButton {
            width: 30
            height: 30
            text: "+"
            buttonType: "secondary"
            onClicked: mapBackground.scaleFactor *= 1.2
        }

        Components.ActionButton {
            width: 30
            height: 30
            text: "-"
            buttonType: "secondary"
            onClicked: mapBackground.scaleFactor /= 1.2
        }
    }
}
